const app = getApp();

Component({
    data: {
        selected: 0, // 默认选中首页
        color: "#999999",
        selectedColor: "#000000",
        list: [{
            pagePath: "/pages/index/index",
            iconPath: "/image/home_.png",
            selectedIconPath: "/image/home.png",
            text: "首页",
            isCenter: false
        }, {
            pagePath: "/pages/photo/photo",
            iconPath: "/image/camera.png",
            selectedIconPath: "/image/camera_.png",
            text: "搜题",
            isCenter: false
        }, {
            pagePath: "/pages/profile/profile",
            iconPath: "/image/my.png",
            selectedIconPath: "/image/my_.png",
            text: "我的",
            isCenter: false
        }]
    },
    attached() {
    },
    ready() {
        this.updateSelectedTab();
    },
    pageLifetimes: {
        show: function () {
            this.updateSelectedTab();
        }
    },
    methods: {
        updateSelectedTab() {
            const pages = getCurrentPages();
            if (pages.length <= 0) return;

            const currentPage = pages[pages.length - 1];
            const currentRoute = '/' + currentPage.route;

            let selectedIndex = -1;
            for (let i = 0; i < this.data.list.length; i++) {
                if (this.data.list[i].pagePath === currentRoute) {
                    selectedIndex = i;
                    break;
                }
            }

            if (selectedIndex !== -1 && this.data.selected !== selectedIndex) {
                this.setData({ selected: selectedIndex });
            } else if (selectedIndex === -1 && currentRoute === '/pages/index/index') {
                this.setData({ selected: 0 });
            }
        },

        switchTab(e) {
            const data = e.currentTarget.dataset;
            const url = data.path;
            const index = parseInt(data.index);

            if (this.data.selected === index) {
                return;
            }

            this.setData({ selected: index });

            wx.switchTab({
                url,
                success: () => {
                    console.log('Tab切换成功:', url);
                },
                fail: (error) => {
                    console.error('Tab切换失败:', error);
                }
            });
        },
        addActivity() {
            wx.navigateTo({
                url: '/pages/photo/photo',
            })
        },
    }
})